<template>
  <div class="article-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文章管理</span>
          <el-button type="primary" @click="handleAdd">添加文章</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类">
            <el-option label="全部" value=""></el-option>
            <el-option label="饮食健康" value="DIET"></el-option>
            <el-option label="运动健康" value="EXERCISE"></el-option>
            <el-option label="心理健康" value="MENTAL"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 文章列表 -->
      <el-table :data="articleList" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            {{ getCategoryLabel(row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="createTime" label="发布时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'PUBLISHED' ? 'success' : 'info'">
              {{ row.status === 'PUBLISHED' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              link 
              :type="row.status === 'PUBLISHED' ? 'warning' : 'success'"
              @click="handleToggleStatus(row)">
              {{ row.status === 'PUBLISHED' ? '下架' : '发布' }}
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 文章编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogType === 'add' ? '添加文章' : '编辑文章'"
      width="80%">
      <el-form 
        :model="articleForm" 
        :rules="rules" 
        ref="articleFormRef"
        label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="articleForm.category" style="width: 100%">
            <el-option label="饮食健康" value="DIET" />
            <el-option label="运动健康" value="EXERCISE" />
            <el-option label="心理健康" value="MENTAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="articleForm.content" 
            type="textarea" 
            :rows="15"
            placeholder="支持 Markdown 格式" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button @click="handleSaveDraft" :loading="submitting">保存草稿</el-button>
          <el-button type="primary" @click="handlePublish" :loading="submitting">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useArticleStore } from '../../stores/article'

const articleStore = useArticleStore()

// 搜索表单
const searchForm = reactive({
  title: '',
  category: ''
})

// 文章列表数据
const articleList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitting = ref(false)
const articleFormRef = ref(null)

// 文章表单
const articleForm = reactive({
  title: '',
  category: '',
  content: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于 10 个字符', trigger: 'blur' }
  ]
}

// 获取分类标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    'DIET': '饮食健康',
    'EXERCISE': '运动健康',
    'MENTAL': '心理健康'
  }
  return categoryMap[category] || category
}

// 获取文章列表
const fetchArticleList = async () => {
  loading.value = true
  try {
    await articleStore.fetchArticleList({
      page: currentPage.value,
      size: pageSize.value,
      title: searchForm.title,
      category: searchForm.category
    })
    articleList.value = articleStore.articleList
    total.value = articleStore.total
  } catch (error) {
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchArticleList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.category = ''
  handleSearch()
}

// 添加文章
const handleAdd = () => {
  dialogType.value = 'add'
  articleForm.title = ''
  articleForm.category = ''
  articleForm.content = ''
  dialogVisible.value = true
}

// 编辑文章
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(articleForm, row)
  dialogVisible.value = true
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!articleFormRef.value) return
  
  await articleFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const data = { ...articleForm, status: 'DRAFT' }
        if (dialogType.value === 'add') {
          await articleStore.createArticle(data)
        } else {
          await articleStore.updateArticle(articleForm.id, data)
        }
        ElMessage.success('保存成功')
        dialogVisible.value = false
        fetchArticleList()
      } catch (error) {
        ElMessage.error(error.message || '保存失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 发布文章
const handlePublish = async () => {
  if (!articleFormRef.value) return
  
  await articleFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const data = { ...articleForm, status: 'PUBLISHED' }
        if (dialogType.value === 'add') {
          await articleStore.createArticle(data)
        } else {
          await articleStore.updateArticle(articleForm.id, data)
        }
        ElMessage.success('发布成功')
        dialogVisible.value = false
        fetchArticleList()
      } catch (error) {
        ElMessage.error(error.message || '发布失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 切换文章状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'PUBLISHED' ? '下架' : '发布'}该文章吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await articleStore.updateArticleStatus(
      row.id, 
      row.status === 'PUBLISHED' ? 'OFFLINE' : 'PUBLISHED'
    )
    ElMessage.success('操作成功')
    fetchArticleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 删除文章
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该文章吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await articleStore.deleteArticle(row.id)
    ElMessage.success('删除成功')
    fetchArticleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchArticleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchArticleList()
}

onMounted(() => {
  fetchArticleList()
})
</script>

<style scoped>
.article-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 